<template>
  <el-card>
    <!-- 面包屑导航 -->
    <div slot="header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <template v-if="$route.params.id">
          <el-breadcrumb-item to="/article">内容管理</el-breadcrumb-item>
          <el-breadcrumb-item>修改文章</el-breadcrumb-item>
        </template>
        <el-breadcrumb-item v-else>发布文章</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 文章表单 -->
    <el-form :model="articleForm" :rules="rules" ref="articleFormRef">
      <!-- 标题输入框 -->
      <el-form-item label="标题" prop="title">
        <el-input
          placeholder="请输入文章标题"
          style="width: 400px"
          v-model="articleForm.title"
        ></el-input>
      </el-form-item>
      <!-- 频道选择框 -->
      <el-form-item label="频道" prop="channel_id">
        <GeekChannel v-model="articleForm.channel_id" />
      </el-form-item>
      <!-- 封面选择 -->
      <el-form-item label="封面" prop="cover">
        <el-radio-group v-model="articleForm.cover.type" @change="clearImage">
          <el-radio :label="1">单图</el-radio>
          <el-radio :label="3">三图</el-radio>
          <el-radio :label="0">无图</el-radio>
          <el-radio :label="-1">自动</el-radio>
        </el-radio-group>
        <!-- 封面图片上传 -->
        <div v-if="articleForm.cover.type===1 || articleForm.cover.type===3">
          <el-upload
          ref="radioRef"
          action=""
         :http-request="uploadFile"
          list-type="picture-card"
          :on-remove="DelTUrl"
          :file-list="fileList"
          :limit="articleForm.cover.type"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        </div>
      </el-form-item>
      <!-- 内容编辑器 -->
      <el-form-item label="内容" prop="content">
        <quillEditor v-model="articleForm.content" @blur="checkContent()"/>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item v-if="$route.params.id">
        <el-button type="primary" @click="Onchange(false)">修改文章</el-button>
        <el-button @click="Onchange(false)">保存草稿</el-button>
      </el-form-item>
      <el-form-item v-else>
        <el-button type="primary" @click="submit(false)">发布文章</el-button>
        <el-button @click="submit(true)">保存草稿</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 2. 导入富文本组件
import { quillEditor } from 'vue-quill-editor'
export default {
  components: {
    quillEditor
  },
  data () {
    // 封面验证规则
    const checkCover = (rule, value, callback) => {
      if (value.type === 1 && value.images.length < 1) {
        return callback(new Error('请上传一张封面图片'))
      } else if (value.type === 3 && value.images.length < 3) {
        return callback(new Error('请上传三张封面图片'))
      }
      callback()
    }
    return {
      // 文章表单数据
      articleForm: {
        title: '', // 文章标题
        content: '', // 文章内容
        cover: {
          type: 1, // 封面类型 -1:自动，0-无图，1-1张，3-3张
          images: [] // 封面图片数组
        },
        channel_id: 0 // 文章所属频道id
      },
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 4, max: 20, message: '文章标题长度在4-20个字符之间', trigger: 'blur' }
        ],
        channel_id: [
          { required: true, message: '请选择文章频道', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        cover: [
          { validator: checkCover, trigger: 'change' }
        ]
      }
    }
  },
  created () {
    // 如果有文章id，则获取文章详情
    if (this.$route.params.id) {
      this.getArticleDetail()
    }
  },
  computed: {
    // 根据封面图片数组生成fileList
    fileList () {
      return this.articleForm.cover.images.map(item => {
        return {
          name: item, url: item, response: item
        }
      })
    }
  },
  methods: {
    // 获取文章详情
    async getArticleDetail () {
      const res = await this.$http.get(`/v1_0/mp/articles/${this.$route.params.id}`)
      // console.log(res)
      this.articleForm = res.data.data
    },
    // 自定义文件上传方法
    async uploadFile (obj) {
      const fd = new FormData()
      fd.append('image', obj.file)
      const res = await this.$http.post('/v1_0/upload', fd)
      // console.log(res)
      this.articleForm.cover.images.push(res.data.data.url)
      this.$refs.articleFormRef.validateField('cover')
      return res.data.data.url
    },
    // 清除封面图片
    clearImage () {
      this.$refs.radioRef?.clearFiles()
      this.articleForm.cover.images = []
    },
    // 删除封面图片
    DelTUrl (file) {
      // console.log('删除的文件', file)
      this.articleForm.cover.images = this.articleForm.cover.images.filter(item => item !== file.response)
      this.$refs.articleFormRef.validateField('cover')
    },
    // 内容编辑器失焦时验证内容
    checkContent () {
      this.$refs.articleFormRef.validateField('content')
    },
    // 提交文章方法
    submit (isTrue) {
      this.$refs.articleFormRef.validate(async (res) => {
        const rul = await this.$http.post('/v1_0/mp/articles?draft=' + isTrue, this.articleForm, {
          params: {
            draft: isTrue
          }
        })
        console.log(rul)
        this.$message.success(isTrue ? '发布成功' : '保存成功')
        this.$router.push('/article')
      })
    },
    // 修改文章方法
    Onchange (isTrue) {
      this.$refs.articleFormRef.validate(async (res) => {
        try {
          const rul = await this.$http.put(`/v1_0/mp/articles/${isTrue}`, this.articleForm, {
            params: {
              draft: isTrue
            }
          })
          console.log(rul)
          this.$message.success(isTrue ? '保存成功' : '修改成功')
          this.$router.push('/article')
        } catch (error) {
          this.$message.success('文章不存在')
          this.$router.push('/article')
        }
      })
    }
  },
  // 路由更新前获取文章详情或重置表单
  beforeRouteUpdate (to, from, next) {
    if (to.params.id) {
      this.getArticleDetail()
    } else {
      this.$refs.articleFormRef.resetFields()
    }
    next()
  }
}
</script>
<style scoped>
::v-deep .ql-editor {
  min-height: 300px;
}
/* 关闭上传组件的动画效果 */
::v-deep .el-upload-list__item {
  transition: none;
}
</style>
